

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="MiaoHao-oops">
  <meta name="keywords" content="">
  
    <meta name="description" content="从计算机组成的角度窥探NEMU是如何运作的。">
<meta property="og:type" content="article">
<meta property="og:title" content="nju-pa摸鱼记4-指令的生命周期">
<meta property="og:url" content="http://miaohao-oops.github.io/2022/02/07/nju-pa%E6%91%B8%E9%B1%BC%E8%AE%B04-%E6%8C%87%E4%BB%A4%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/index.html">
<meta property="og:site_name" content="Miao&#39;s Blog">
<meta property="og:description" content="从计算机组成的角度窥探NEMU是如何运作的。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-02-07T05:48:32.000Z">
<meta property="article:modified_time" content="2023-10-25T04:38:40.119Z">
<meta property="article:author" content="MiaoHao-oops">
<meta property="article:tag" content="C语言">
<meta property="article:tag" content="计算机组成原理">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>nju-pa摸鱼记4-指令的生命周期 - Miao&#39;s Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"miaohao-oops.github.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"appId":"y7tlaLEOoW5C1xBYm8VBo64Q-gzGzoHsz","appKey":"F7gylUefEEtQk24FEbvgfnBi","server_url":"https://y7tlaleo.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":true}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"><link rel="alternate" href="/atom.xml" title="Miao's Blog" type="application/atom+xml">
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>MiaoHao-oops</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="nju-pa摸鱼记4-指令的生命周期">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-02-07 13:48" pubdate>
        2022年2月7日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      17 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">nju-pa摸鱼记4-指令的生命周期</h1>
            
            <div class="markdown-body">
              <h2 id="一前言">一、前言</h2>
<p>在之前的3篇专栏中，主要探讨了NEMU中一些巧妙的宏定义，以及关于计算模型的思考。从本篇开始，将专注于“模拟器如何模拟真实计算机”这一话题。计算机最基础、最核心的功能是执行指令，因此执行指令也是NEMU模拟器最基本的功能。</p>
<h2 id="二计算机中指令的生命周期">二、计算机中指令的生命周期</h2>
<p>对于精简指令集系统，五级流水线是一种经典的CPU核结构，它将一条指令的处理过程分为5个阶段：</p>
<ul>
<li><p>取指：维护PC寄存器，发起访存请求从内存中取出指令；</p></li>
<li><p>译码：翻译取出的指令，确定指令的操作方法和操作对象；</p></li>
<li><p>执行：通过运算部件（如ALU，乘法器等）对操作对象进行算</p></li>
<li><p>访存：若为访存类指令，则在这个阶段进行访存；</p></li>
<li><p>写回：将指令的运算、访存等结果写回目的寄存器。</p></li>
</ul>
<p>这五个阶段轮流往复地运行，计算机便能自动地运行下去。</p>
<h2 id="三nemu中指令的生命周期">三、NEMU中指令的生命周期</h2>
<p>在真实的CPU中，为了提升效率，在取指完成后PC跳转到紧接着当前指令的下一条指令继续取指，如果遇到跳转指令，可以冲刷流水线或者使用分支预测等技术增大取指的正确率。而在模拟器中则没有对于性能的要求，完全可以等到指令执行结束再更新PC，然后开始取下一条指令，在NEMU中，指令执行阶段的划分为：</p>
<ul>
<li><p>取指：通过PC值访问“内存”，取出指令；</p></li>
<li><p>译码：分析指令，确定操作方法和操作数；</p></li>
<li><p>执行：通过对应的处理函数对操作数进行处理，同时将结果写回“寄存器”；</p></li>
<li><p>更新PC：根据指令的执行情况更新PC，此PC一定是正确的PC。</p></li>
</ul>
<p>下面是一条语句在NEMU中的执行过程：</p>
<ol type="1">
<li><p>NEMU调用定义在<code>src/cpu/cpu-exec.c</code>中的<code>cpu_exec()</code>函数，该函数将反复进行取指、译码、执行、更新PC这个过程，直到遇到停机、断点或是什么别的情况。</p></li>
<li><p><code>cpu_exec()</code>函数的核心是一个死循环，其中包括了<code>fetch_decode_exec_updatepc()</code>函数，该函数的定义如下：</p></li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">// src/cpu/cpu-exec.c</span><br><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fetch_decode_exec_updatepc</span><span class="hljs-params">(Decode *s)</span> </span>&#123;<br>  fetch_decode(s, cpu.pc);  <span class="hljs-comment">// fetch and decode</span><br>  s-&gt;EHelper(s);            <span class="hljs-comment">// exec</span><br>  cpu.pc = s-&gt;dnpc;         <span class="hljs-comment">// update pc</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p>它将取指译码、执行和更新PC解构，分别对应函数中的三条语句。</p>
<ol start="3" type="1">
<li>首先调用<code>fetch_decode()</code>函数，该函数的核心功能可以简化如下：</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">// src/cpu/cpu-exec.c</span><br><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">fetch_decode</span><span class="hljs-params">(Decode *s, <span class="hljs-keyword">vaddr_t</span> pc)</span> </span>&#123;<br>  s-&gt;pc = pc;<br>  s-&gt;snpc = pc;<br>  <span class="hljs-keyword">int</span> idx = isa_fetch_decode(s);<br>  s-&gt;dnpc = s-&gt;snpc;<br>  s-&gt;EHelper = g_exec_table[idx];<br>&#125;<br></code></pre></td></tr></table></figure>
<p>在<code>fetch_decode()</code>函数中，通过<code>isa_fetch_decode()</code>函数得到指令所对应的序号，该序号和这条指令对应处理函数在列表中的下标相同，然后为函数指针<code>s-&gt;EHelper</code>赋值为对应的处理函数。</p>
<ol start="4" type="1">
<li>进入<code>isa_fetch_decode()</code>函数，取指和译码进一步被解构，<code>instr_fetch()</code>函数负责与内存交互取指令；<code>table_main()</code>函数是译码函数，将取回的函数和模式串一一比对，若匹配成功则返回该指令对应的序号，若失败则返回一个无效指令序号，这将导致NEMU产生运行异常报给用户。同时在译码时，也将获取该指令的所有操作数，包括立即数和寄存器，它们都将被存在<code>Decode</code>结构中。</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">// src/isa/risCV64/instr/decode.c</span><br><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">isa_fetch_decode</span><span class="hljs-params">(Decode *s)</span> </span>&#123;<br>  s-&gt;isa.instr.val = instr_fetch(&amp;s-&gt;snpc, <span class="hljs-number">4</span>);<br>  <span class="hljs-keyword">int</span> idx = table_main(s);<br>  <span class="hljs-keyword">return</span> idx;<br>&#125;<br></code></pre></td></tr></table></figure>
<ol start="5" type="1">
<li>现在返回到<code>fetch_decode_exec_updatepc()</code>函数中，它的第二条语句调用了<code>s-&gt;EHelper()</code>函数执行该指令，这些执行函数被定义在<code>src/isa/$ISA/instr</code>下的若干<code>.h</code>文件中，比如说lui指令的处理函数：</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-comment">// src/isa/$ISA/instr/compute.h</span><br>def_EHelper(lui) &#123;<br>  rtl_li(s, ddest, id_src1-&gt;imm);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>它是由更加细化的rtl级函数<code>rtl_li</code>所完成的，所有指令的终点都是若干rtl函数，也就是将指令拆解成“微指令”。</p>
<ol start="6" type="1">
<li>执行完<code>s-&gt;EHelper()</code>后，语句</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs c">cpu.pc = s-&gt;dnpc;         <span class="hljs-comment">// update pc</span><br></code></pre></td></tr></table></figure>
<p>将完成更新PC的过程。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/NEMU/">NEMU</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/C%E8%AF%AD%E8%A8%80/">C语言</a>
                    
                      <a class="hover-with-bg" href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BB%84%E6%88%90%E5%8E%9F%E7%90%86/">计算机组成原理</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/29/LR-0-%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">LR(0)分析方法</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/02/05/nju-pa%E6%91%B8%E9%B1%BC%E8%AE%B03-nemu%E4%B8%AD%E5%AE%8F%E7%9A%84%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/">
                        <span class="hidden-mobile">nju-pa摸鱼记3-NEMU中宏的源码阅读</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"y7tlaLEOoW5C1xBYm8VBo64Q-gzGzoHsz","appKey":"F7gylUefEEtQk24FEbvgfnBi","path":"window.location.pathname","placeholder":"此处留言","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> && <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
